/**
 * All rights Reserved, Designed By junglead.cn
 * @package cn.junglead.common.utils
 * @title IdWorker.java
 * @date 2020年12月3日
 */
package cn.junglead.common.utils;

/**
 * 分布式id生成工具类
 * @author Gary.Wang
 * @version 1.0
 */
public final class IdWorker {

	private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    private long lastTimestamp = -1L;
    private final long sequenceBits = 12L;
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;


    /**
	 * 1.1 工厂id
	 */
	private long workerId;
	
	/**
	 * 1.2 数据id
	 */
    private long datacenterId;
    
    /**
     * 1.3 序列
     */
    private long sequence;
    
    
    /**
     * 1.1 获取当前时间戳
     * @return 返回当前时间戳
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }
    /**
     * 1.2 下一次便宜时间
     * @param lastTimestamp 最晚时间戳
     * @return 返回下一个时间
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }
    
    /**
     * 2.1 唯一的构造函数
     * @param workerId 工厂id
     * @param datacenterId 数据id
     * @param sequence 序列
     */
    public IdWorker(long workerId, long datacenterId, long sequence) {
        // sanity check for workerId
        // 这儿不就检查了一下，要求就是你传递进来的机房id和机器id不能超过32，不能小于0
        // 这个是二进制运算，就是 5 bit最多只能有31个数字，也就是说机器id最多只能是32以内
        long maxWorkerId = ~(-1L << workerIdBits);
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        // 这个是一个意思，就是 5 bit最多只能有31个数字，机房id最多只能是32以内
        long maxDatacenterId = ~(-1L << datacenterIdBits);
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        System.out.printf(
                "worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerId %d",
                timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);
        this.setWorkerId(workerId);
        this.setDatacenterId(datacenterId);
        this.setSequence(sequence);
    }
    /**
     * 2.2 线程安全的获取id的方法
     * @return 返回生成的id
     */
    public synchronized long nextId() {
        long timestamp = timeGen();  // 获取当前时间戳

        if (timestamp < lastTimestamp) {
            System.err.printf("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp);
            throw new RuntimeException(String.format(
                    "Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            // 这个意思是说一个毫秒内最多只能有4096个数字
            // 无论你传递多少进来，这个位运算保证始终就是在4096这个范围内，避免你自己传递个sequence超过了4096这个范围
            long sequenceMask = ~(-1L << sequenceBits);
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        // 这儿记录一下最近一次生成id的时间戳，单位是毫秒
        lastTimestamp = timestamp;

        // 这儿就是将时间戳左移，放到 41 bit那儿；
        // 将机房 id左移放到 5 bit那儿；
        // 将机器id左移放到5 bit那儿；将序号放最后12 bit；
        // 最后拼接起来成一个 64 bit的二进制数字，转换成 10 进制就是个 long 型
        long twepoch = 1288834974657L;
        long datacenterIdShift = sequenceBits + workerIdBits;
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift)
                | (workerId << sequenceBits) | sequence;
    }
	public long getWorkerId() {
		return workerId;
	}
	public void setWorkerId(long workerId) {
		this.workerId = workerId;
	}
	public long getDatacenterId() {
		return datacenterId;
	}
	public void setDatacenterId(long datacenterId) {
		this.datacenterId = datacenterId;
	}
	public long getSequence() {
		return sequence;
	}
	public void setSequence(long sequence) {
		this.sequence = sequence;
	}
}
